package com.atguigu.distributed.lock.leecode;

/**
 * 冒泡排序
 */
public class BurSorted {
    public static void sort(int array[]){
        for (int i = 0; i < array.length; i++) {
            //有序标记，每一轮的初始值都是true
            boolean isSorted = true;
            for (int j = 0; j < array.length-1-i; j++) {
                int tmp = 0;
                if(array[j]>array[j+1]){
                    tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                    //因为发生了交换，所以不是有序的，标记变为false
                    isSorted = false;
                }
            }
            if(isSorted){
                break;
            }
        }
    }
    public static void sort2(int array[]){
        int lastIndex = 0;
        int sortBorder = array.length-1;
        for (int i = 0; i < array.length; i++) {
            boolean isSorted = true;
            for (int j = 0; j < sortBorder; j++) {
                int tmp = 0;
                if(array[j]>array[j+1]){
                    tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = array[j];
                    lastIndex = j;
                }
                //因为发生了交换，所以不是有序的，标记变为false
                isSorted = false;
            }
            sortBorder = lastIndex;
            if(isSorted){
                break;
            }
        }
    }
    //龙舌酒排序
    public static void sort3(int array[]){
        int tmp = 0;
        for (int i = 0; i < array.length/2; i++) {
            boolean isSorted = true;
            //奇数轮，从左向右比较和交换
            for (int j = i; j < array.length-i-1; j++) {
                if(array[j]>array[j+1]){
                    tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                    isSorted = false;
                }
            }
            if(isSorted){
                break;
            }
            //在偶数轮之前，将isStorted重新标记为true
            isSorted = true;
            //偶数轮，从右往左比较和交换
            for (int j = array.length-1-i; j > i; j--) {
                if(array[j] < array[j-1]){
                    tmp = array[j];
                    array[j] = array[j-1];
                    array[j-1]=tmp;
                    isSorted = false;
                }
            }
            if(isSorted){
                break;
            }
        }
    }
}
